package com.qf.cardlikeboot.controller;

import com.qf.cardlikeboot.entity.User;
import com.qf.cardlikeboot.service.UserService;
import com.qf.cardlikeboot.utils.MailUtils;
import com.wf.captcha.ChineseGifCaptcha;
import lombok.RequiredArgsConstructor;
import org.apache.commons.lang3.RandomStringUtils;
import org.apache.tomcat.util.http.fileupload.ByteArrayOutputStream;
import org.springframework.core.io.ByteArrayResource;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;

import javax.servlet.http.HttpSession;
import javax.swing.text.html.HTML;
import java.util.Objects;
import java.util.Random;

/**
 * @author 钻五大人
 * @date 2022/5/22 17:51
 */
@Controller
//@RequiredArgsConstructor主要是对当前类中带有final 的属性进行属性注入。
@RequiredArgsConstructor
public class UserController {

    private final UserService userService;

    @GetMapping("/")
    public String index(){
        return "index";
    }

    @GetMapping("/sendEmail")
    public String sendEmail(String email, HttpSession session){
        // 生成一个验证码,随机数
        String code = RandomStringUtils.randomNumeric(5);
        // 把验证码放入到session中,下次登陆请求进来时可以比对验证码
        session.setAttribute("code",code);
        // 发送邮件
        MailUtils.sendMail(email,"名片系统验证码","您的验证码是:"+code);
        return "成功";
    }

    @PostMapping("/login")
    public String login(String username, String password, String code, HttpSession session, Model model){
        String sessionCode = (String) session.getAttribute("code");
        // 比用户输入的验证码是否正确
        if(Objects.equals(sessionCode,code)){
            // 如果正确,再调用业务登陆方法
            User login = userService.login(username,password);
            session.setAttribute("username",username);
            if (Objects.nonNull(login)){
                return "welcome";
            }else {
                model.addAttribute("msg","用户名或密码错误");
                // 登陆错误的提示
                return "index";
            }
        } else{
            model.addAttribute("msg","邮箱验证码错误");
            // 登陆错误的提示
            return "index";
        }
    }

}
